import 'dart:io';
import 'package:FineArt/constants.dart';
import 'package:FineArt/core/api/material_api.dart';
import 'package:FineArt/core/api/resource_api.dart';
import 'package:FineArt/core/utils/toast.dart';
import 'package:FineArt/page/imageview/AgencyImagePreview.dart';
import 'package:FineArt/page/imageview/RoundCheckBox.dart';
import 'package:FineArt/page/tab/CreateFolder.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:FineArt/utils/sputils.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:image_picker/image_picker.dart';

///我的素材 学生 老师都可以跳转到这里
class MyMaterialFolderPage extends StatefulWidget {
  MyMaterialFolderPage();

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _MyMaterialFolderPageState();
  }
}

class _MyMaterialFolderPageState extends State<MyMaterialFolderPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // buildAddItem();
    _getFolder();
  }

  int _count = 3;
  int _pId = 0;
  int level = 1;
  int _lastFolderId = 0;
  FileDirBean _lastFb;
  bool isLoadedFolder = false;
  List<int> pidArr = [];

  int currentPage = 0;
  bool isChooseMode = false;
  int lastChooseFileIndex=-1;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    LogUtil.d("didChangeDependencies>>>>>>");
    if (CreateFolderPage.isCreateFolder) {
      CreateFolderPage.isCreateFolder = false;
      new Future.delayed(new Duration(seconds: 3), _getFolder());
    }
  }

  @override
  void didUpdateWidget(StatefulWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    LogUtil.d("didUpdateWidget>>>>>>");
  }

  _getFolder() {
    LogUtil.d("getFolder _lastFolderId>>>$_lastFolderId");
    MaterialApi().getDir("PRIVATE", _lastFolderId).then((result) {
      if (result.code == 200) {
        serverFolderCount = result.data.length;
        allFolders = result.data;
        setState(() {
          currentFolderFile.clear();
          for (int i = 0; i < result.data.length; i++) {
            FileDirBean dir = result.data[i];
            FolderBean fb =
                FolderBean(folderAssetsUrl, dir.label, dir.id.toString());
            fb.dir = dir;
            _pId = dir.pId;
            currentFolderFile.add(fb);
          }
        });
        LogUtil.d("getFolder len>>>${currentFolderFile.length}");
        currentPage = 0;
        _getFiles();
        isLoadedFolder = true;
      }
    });
  }

  _reLoadCurFolder(List<FileDirBean> fbList, int pid) {
    setState(() {
      currentFolderFile.clear();
      if (fbList != null) {
        for (int i = 0; i < fbList.length; i++) {
          FileDirBean dir = fbList[i];
          FolderBean fb =
              FolderBean(folderAssetsUrl, dir.label, dir.id.toString());
          fb.dir = dir;
          currentFolderFile.add(fb);
        }
      }
      buildAddItem();
      LogUtil.d("_reLoadCurFolder len>>>${currentFolderFile.length}");
    });
  }

  //返回上级目录
  _getPreFolderByPid(int pid) {
    FileDirBean targetFb = _lastFb;
    //获取父级的同级兄弟
    LogUtil.d("_getPreFolderByPid pid  $pid");
    // if(targetFb!=null) {
    //    bool  existSuperPar;
    //    List<FileDirBean> fbList=[];
    //    LogUtil.d("targetFb pid  $pid");
    //     for (int i = 0; i < allFolders.length; i++) {
    //       FileDirBean par = _getFolderBeanByPid(
    //           targetFb.pId, allFolders[i]);
    //       if (par != null) {
    //           fbList.add(par);
    //           if(_lastFolderId==par.id){
    //               _lastFolderId = par.pId;
    //           }
    //       }
    //       LogUtil.d("targetFb 00  $par $i");
    //     }
    //    LogUtil.d("targetFb 011  $existSuperPar fbList.length ${fbList.length}");
    //     if(existSuperPar==null && fbList.length>0){
    //       for (int i = 0; i < allFolders.length; i++) {
    //         FileDirBean fdb = _getParentFolderBeanById(_lastFolderId,allFolders[i]);
    //           if(fdb!=null){
    //             _pId=fdb.pId;
    //             _lastFb=fdb;
    //             break;
    //           }
    //       }
    //
    //       _reLoadCurFolder(fbList, targetFb.pId);
    //     }
    // }
    // else{
    //   LogUtil.d("targetFb null");
    // }
    // _getFiles();
    _lastFolderId = pidArr.removeLast();
    _getFolder();
  }

  FileDirBean _getFolderBeanByPid(int pid, FileDirBean fb) {
    LogUtil.d("_getFolderBeanByPid begin  ${fb.id}>>$pid>>>>");
    if (fb.pId == pid) {
      return fb;
    }
    if (fb.children == null || fb.children.length == 0) return null;
    for (int i = 0; i < fb.children.length; i++) {
      FileDirBean tmp = _getFolderBeanByPid(pid, fb.children[i]);
      if (tmp != null) {
        return tmp;
      }
    }
    return null;
  }

  FileDirBean _getParentFolderBeanById(int pid, FileDirBean fb) {
    LogUtil.d("_getFolderBeanByPid begin  ${fb.id}>>$pid>>>>");
    if (fb.id == pid) {
      return fb;
    }
    FileDirBean tfb;
    if (fb.children == null || fb.children.length == 0) return null;
    for (int i = 0; i < fb.children.length; i++) {
      tfb = _getParentFolderBeanById(pid, fb.children[i]);
      if (tfb != null) {
        break;
      }
    }
    return tfb;
  }

  _getFiles() {
    LogUtil.d("_getFiles begin  aa>>${currentFolderFile.length}>>>>>>");
    MaterialApi()
        .fileList(_lastFolderId, currentPage, PAGE_SIZE)
        .then((result) {
      if (result.code == 200) {
        int len = result.data.list.length;
        if (len > 0) {
          if (currentFolderFile.contains(beanAdd)) {
            currentFolderFile.remove(beanAdd);
          }
        }
        LogUtil.d("_getFiles len 00  $len>>>>>>");
        List<FolderBean> fList = [];
        for (int i = 0; i < len; i++) {
          FileEntity file = result.data.list[i];
          FolderBean fb = FolderBean(
              file.urlThumb, file.name, file.id.toString(),
              largeUrl: file.urlSource);
          fb.file = file;
          fb.isFile = true;
          fList.add(fb);
        }
        currentPage = result.data.pageIndex + 1;

        setState(() {
          // for(int i=0;i<currentFolderFile.length;i++){
          //   FolderBean fb= currentFolderFile[i];
          //   if(fb.isFile){
          //     currentFolderFile.removeAt(i);
          //     i--;
          //   }
          // }
          // if(currentFolderFile.length>0)
          // currentFolderFile.removeLast();
          if (fList.length > 0) {
            currentFolderFile.addAll(fList);
          }
          buildAddItem();
        });

        LogUtil.d("_getFiles ${currentFolderFile.length}>>>>>>");
      }
    });
  }

  Future<bool> _requestPop() {
    print("_requestBack $_pId");
    level--;
    if (level > 0) {
      LogUtil.d("返回上一文件夹");

      _getPreFolderByPid(_pId);
      return Future.value(false);
    }

    print("_requestBack111");
    if (Navigator.canPop(context)) {
      Navigator.pop(context);
    } else {
      SystemNavigator.pop();
    }
    return Future.value(false);
  }

  Widget _buildAppbar() {
    String role = SPUtils.getRole();
    bool isTeacher = "teacher" == role;
    return AppBar(
      title: Text(
        "我的素材",
        style: TextStyle(color: text_black, fontSize: setSp(18)),
      ),
      backgroundColor: Colors.white,
      centerTitle: true,
      brightness: Brightness.light,
      iconTheme: IconThemeData(
        color: text_black, //修改颜色
      ),
      elevation: 0,
      actions: <Widget>[getAppBarRightActionItem(isTeacher)],
    );
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    var width = MediaQuery.of(context).size.width * 0.76;
    return WillPopScope(
        onWillPop: _requestPop,
        child: Scaffold(
          appBar: _buildAppbar(),
          body: Column(
            children: [
              // Padding(
              //     padding: EdgeInsets.symmetric(
              //         vertical: 0, horizontal: getPortraitSWidth(16)),
              //     child: Column(
              //       children: [
              //         Expanded(child: _buildRefreshGridView()),
              //       ],
              //     )),
              Expanded(child: _buildRefreshGridView()),
              buildChooseBottomLine()
            ],
          ),
        ));
  }

  Widget getAppBarRightActionItem(bool isTeacher) {
    // if (isTeacher) {
    //   return InkWell(
    //     child: Padding(
    //         padding: EdgeInsets.only(top: getPortraitSHeight(15), right: 10),
    //         child: Text(
    //           isChooseMode ? "取消" : "管理",
    //           style: TextStyle(fontSize: setSp(16), color: text_black),
    //         )),
    //     onTap: () {
    //       setState(() {
    //         isChooseMode = !isChooseMode;
    //         lastChooseFileIndex=-1;
    //       });
    //     },
    //   );
    // }
    // 隐藏的菜单
    // else{
      return PopupMenuButton<String>(
        itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
          this.SelectView(Icons.select_all_sharp, '管理', 'A'),
          this.SelectView(Icons.photo_camera_outlined, '本地上传', 'C'),
        ],
        onSelected: (String action) {
          // 点击选项的时候
          switch (action) {
            case 'A':
              LogUtil.d("A");
              setState(() {
                isChooseMode = true;
              });
              break;
            case 'B':
              LogUtil.d("B");
              break;
            case 'C':
              LogUtil.d("c");
              _showBottomMenu(context);
              break;
          }
        },
        offset: Offset(100, 100),
      );
    // }
  }

  bool loading = false;

  Widget _buildRefreshGridView() {
    MaterialHeader header =
        MaterialHeader(completeDuration: new Duration(milliseconds: 200));
    return EasyRefresh.custom(
      header: header,
      footer: MaterialFooter(),
      onRefresh: () async {
        _getFolder();
      },
      onLoad: () async {
        if (loading) return;
        loading = true;
        new Future.delayed(Duration(seconds: 1), () {
          loading = false;
          _getFiles();
        });
      },
      slivers: <Widget>[
        SliverToBoxAdapter(
          child: RefreshIndicator(
            onRefresh: () async {
              // _getFolder();
            },
            child: _buildGridView(),
          ),
        ),
      ],
    );
  }

  Widget _buildGridView() {
    double width = MediaQuery.of(context).size.width * 0.98;
    return GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3, //每行三列
          childAspectRatio: 1.0, //显示区域宽高相等
          crossAxisSpacing: 3.0,
          // 定义行边距
          mainAxisSpacing: 3.0,
        ),
        shrinkWrap: true,
        controller: new ScrollController(),
        itemCount: currentFolderFile.length,
        itemBuilder: (context, index) {
          return getFolderItem(index, () {
            LogUtil.d("item click $index");
            FolderBean fb = currentFolderFile[index];
            if (fb.isFile) {
              //文件的跳转 todo
              // Resource resource =
              // new Resource(type: 1, id: fb.file.id);
              // TeacherCourseView.Jump2CourseView(fb.file.urlSource,fb.file.id, context);

              List<AgencyResource> fs = [];
              int idx = 0;
              for (FolderBean item in currentFolderFile) {
                if (item.isFile) {
                  AgencyResource fr = new AgencyResource(
                      resid: item.file.id,
                      restype: int.parse(fb.file.type),
                      url: fb.file.urlThumb,
                      title: fb.file.name);
                  fs.add(fr);
                  if (fr.resid == fb.file.id) {
                    idx = fs.length - 1;
                  }
                }
              }
              AgencyImagePreview.JumpToPreview(
                  0, idx, fs, context, _lastFolderId);

              // LargePhotoView.Jump2LargeView(fb.largeUrl, context);

            } else {
              if (index == currentFolderFile.length - 1) {
                //创建目录
                LogUtil.d("create dir  pid $_pId");
                Navigator.of(context)
                    .push(MaterialPageRoute(builder: (context) {
                  return CreateFolderPage(pId: _lastFolderId);
                }));
              } else {
                //进入下一级目录
                _lastFb = fb.dir;
                _pId = fb.dir.pId;
                _lastFolderId = fb.dir.id;
                pidArr.add(_pId);
                level++;
                LogUtil.d("next dir  pid $_pId");
                _getFolder();
                // _reLoadCurFolder(_lastFb.children, _pId);
                // _getFiles();
              }
            }
          });
        });
  }

  int serverFolderCount = 1;

// 返回每个隐藏的菜单项
  SelectView(IconData icon, String text, String id) {
    return new PopupMenuItem<String>(
        value: id,
        child: new Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            new Icon(icon, color: text_black),
            new Text(text),
          ],
        ));
  }

  Widget getFolderItem(int index, Function onTab) {
    FolderBean fd = currentFolderFile[index];
    if (fd.name == null) {
      fd.name = "默认";
    }

    bool isAdd = index == currentFolderFile.length - 1;
    return InkWell(
        onTap: onTab,
        child: Container(
          child: Stack(alignment: Alignment.center, children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                fd.isFile
                    ? Image(
                        fit: BoxFit.cover,
                        width: getPortraitSWidth(80),
                        height: getPortraitSHeight(90),
                        image: CachedNetworkImageProvider(
                          fd.imageUrl,
                        ))
                    : Image.asset(
                        fd.imageUrl,
                        width: isAdd
                            ? getPortraitSWidth(45)
                            : getPortraitSWidth(59.5),
                      ),
                SizedBox(
                  height: 5,
                ),
                getItemBottomText(isAdd, fd.isFile, fd.name)
              ],
            ),
            Positioned(
                bottom: getPortraitSHeight(30),
                right: 10,
                child: (isChooseMode & !isAdd)
                    ? RoundCheckBox(
                        value: currentFolderFile[index].isCheck,
                        isRadio: true,
                        onChanged: (bool val) {
                          setState(() {
                            for (int i = 0; i < currentFolderFile.length; i++) {
                              currentFolderFile[i].isCheck = false;
                            }
                            currentFolderFile[index].isCheck = val;
                            lastChooseFileIndex=index;
                          });
                        })
                    : Text("")),
          ]),
        ));
  }

  Widget getItemBottomText(bool isAdd, bool isFile, String name) {
    if (isAdd) {
      return SizedBox(
        height: 12,
      );
    } else if (isFile) {
      name = "";
    }
    return Text(
      name ?? "默认",
      textAlign: TextAlign.center,
      style: TextStyle(color: text_black, fontSize: setSp(12), height: 1),
    );
  }

  List<FileDirBean> allFolders = [];
  List<FolderBean> currentFolderFile = [];
  String folderAssetsUrl = "assets/images/icon_folder.png";

  // String addAssetsUrl = "assets/images/icon_add_black.png";

  FolderBean beanAdd =
      FolderBean("assets/images/icon_add_black.png", null, null);

  void buildAddItem() {
    if (currentFolderFile.contains(beanAdd)) return;
    currentFolderFile.add(beanAdd);
    LogUtil.d("buildAddItem ${currentFolderFile.length}");
  }

  Widget buildChooseBottomLine() {
    if (!isChooseMode)
      return SizedBox(
        height: 1,
      );
    return Row(
      children: [
        Expanded(
            child: FlatButton(
          height: getPortraitSHeight(49),
          color: Colors.white,
          child: Text(
            "修改",
            style: TextStyle(color: text_black, fontSize: setSp(18)),
          ),
          onPressed: () {
            if(lastChooseFileIndex<0){
              ToastUtils.toast("你还没有选择文件或者文件夹");
              return;
            }
            setState(() {
              isChooseMode=false;
            });
            Navigator.of(context).push(MaterialPageRoute(builder: (context) {
              return CreateFolderPage(pId: _lastFolderId, updateFolder: currentFolderFile[lastChooseFileIndex]);
            }));
          },
        )),
        Expanded(
            child: FlatButton(
          height: getPortraitSHeight(49),
          color: Colors.redAccent,
          child: Text(
            "移除",
            style: TextStyle(color: Colors.white, fontSize: setSp(18)),
          ),
          onPressed: () {
            if(lastChooseFileIndex<0){
              ToastUtils.toast("你还没有选择文件或者文件夹");
              return;
            }
            deleteConfirm();
          },
        ))
      ],
    );
  }

  void deleteConfirm() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('提示'),
            content: Text('确认要移除当前文件？'),
            actions: <Widget>[
              FlatButton(
                child: Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              FlatButton(
                child: Text('确认'),
                onPressed: () {
                FolderBean fb= currentFolderFile[lastChooseFileIndex];
                if(fb.isFile){
                  ResourceApi().deleteFavorite(fb.file.id).then((result) {
                    if (result.code == 200) {
                      ToastUtils.toast("${result.msg}");
                      new Future.delayed(new Duration(seconds: 1), _getFolder());
                    } else {
                      ToastUtils.toast("移除失败 ${result.msg}");
                    }
                  });;
                }
                else{
                  List<int> ids=new List();
                  ids.add(fb.dir.id);
                  DirDelRequestBody delBody=DirDelRequestBody(ids);
                  MaterialApi().deleteDir(delBody).then((result) {
                    if (result.code == 200) {
                      ToastUtils.toast("${result.msg}");
                      new Future.delayed(new Duration(seconds: 1), _getFolder());
                    } else {
                      ToastUtils.toast(" ${result.msg}");
                    }
                  });
                }
                },
              ),
            ],
          );
        });
  }

//弹出底部菜单
  void _showBottomMenu(BuildContext context) {
    LogUtil.d("_showBottomMenu");
    showModalBottomSheet(
        context: context,
        //isScrollControlled: true,//设为true，此时为全屏展示

        builder: (BuildContext context) {
          return Container(
            color: Colors.white,
            height: 180,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                // ListTile(
                //   title: Text('拍照',
                //       textAlign: TextAlign.center,
                //       style: TextStyle(fontSize: 16, color: text_black)),
                //   onTap: () {
                //     _takePhoto();
                //     Navigator.pop(context);
                //   },
                // ),
                // Divider(
                //   height: 1,
                // ),
                ListTile(
                  title: Text('相册',
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 16, color: text_black)),
                  onTap: () {
                    _openPhotoAlbum();
                    Navigator.pop(context);
                  },
                ),
                Container(
                  color: bg_divider,
                  height: 10,
                ),
                ListTile(
                  title: Text('取消',
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 16, color: text_black)),
                  onTap: () {
                    Navigator.pop(context);
                  },
                ),
              ],
            ),
          );
        });
  }

  PickedFile _image;
  final ImagePicker _picker = ImagePicker();

  ///拍照
  Future _takePhoto() async {
    PickedFile image = await _picker.getImage(source: ImageSource.camera);
    if (image != null) {
      final File file = File(image.path);
      _uploadFIle(file);
      LogUtil.d("_takePhoto obj  ${image.path}");
      _cropImage(image);
    }
  }

  //上传
  _uploadFIle(File f) {
    MaterialApi().upload(1, "PRIVATE", _lastFolderId, f).then((result) {
      if (result.code == 200) {
        ToastUtils.toast("上传成功");
        new Future.delayed(new Duration(seconds: 5), _getFolder);
      } else {
        ToastUtils.toast("上传失败${result.msg}");
      }
    });
  }

  ///打开相册
  Future _openPhotoAlbum() async {
    PickedFile image = await _picker.getImage(source: ImageSource.gallery);
    if (image != null) {
      LogUtil.d("_openPhotoAlbum obj  ${image.path}");
      final File file = File(image.path);
      _uploadFIle(file);
      _cropImage(image);
    }
  }

//剪裁
  _cropImage(PickedFile imageFile) async {
    // setState(() {
    //   _image = imageFile;
    // });
  }
}

class FolderBean {
  FileDirBean dir;
  FileEntity file;
  String imageUrl;
  String name;
  String id;
  bool isCheck = false;
  bool isFile = false;
  String largeUrl;

  FolderBean(this.imageUrl, this.name, this.id, {this.largeUrl});
}
